package com.springmvc.netty.server.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.springmvc.netty.server.IServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class WebSocketServer implements IServer {

	private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

	@Override
	public void serverStart(int port) {
		LOGGER.info("开始启动websocket...");
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(bossGroup, workerGroup);
			serverBootstrap.channel(NioServerSocketChannel.class);
			serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
			serverBootstrap.childHandler(new WebSocketChannelInitializer());

			ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
		LOGGER.info("完成启动websocket...");
	}

	@Override
	public void serverStop() {
		// TODO Auto-generated method stub
	}

	public static void main(String[] args) {
		WebSocketServer websocketServer = new WebSocketServer();
		websocketServer.serverStart(8989);
	}

}